package com.tt.pay.wx

import android.content.Context
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.tt.pay.impl.IPay
import com.tt.pay.PayResultCallBack

object WXPay : IPay<WXParams> {


    //未安装微信或微信版本过低
    const val NO_OR_LOW_WX = 1
    //支付参数错误
    const val ERROR_PAY_PARAM = 2
    //支付失败
    const val ERROR_PAY = 3


    private var mWXApi: IWXAPI? = null
    private var payCallback: PayResultCallBack? = null


    override fun doPay(context: Context, params: WXParams, callBack: PayResultCallBack?) {
        payCallback = callBack
        init(context)
        if (!check()) {
            payCallback?.onError(NO_OR_LOW_WX)
            return
        }

        if (!checkParams(params)) {
            payCallback?.onError(ERROR_PAY_PARAM)
            return
        }


        mWXApi!!.registerApp(params.appId)


        val req = PayReq()
        req.appId = params.appId
        req.partnerId = params.partnerId
        req.prepayId = params.prepayId
        req.packageValue = params.`package`
        req.nonceStr = params.nonceStr
        req.timeStamp = params.timestamp
        req.sign = params.sign

        mWXApi!!.sendReq(req)

    }

    internal fun getWXApi():IWXAPI? = mWXApi


    internal fun onResp(resp: BaseResp) {


        if (resp.type == ConstantsAPI.COMMAND_PAY_BY_WX) {
            when (resp.errCode) {
                BaseResp.ErrCode.ERR_OK -> {
                    //支付成功
                    payCallback?.onSuccess()
                }
                BaseResp.ErrCode.ERR_USER_CANCEL -> {
                    //取消支付
                    payCallback?.onCancel()
                }
                else -> {
                    //支付失败
                    payCallback?.onError(ERROR_PAY, "${resp.errCode}", resp.errStr)
                }
            }

            payCallback = null

        }


    }


    private fun init(context: Context) {
        if (mWXApi == null) {
            mWXApi = WXAPIFactory.createWXAPI(context, null)
        }
    }


    private fun check() =
        mWXApi!!.isWXAppInstalled && mWXApi!!.wxAppSupportAPI >= Build.PAY_SUPPORTED_SDK_INT


    /**
     * 检查参数的有效性
     * return true : 有效
     * return false :无效
     */
    private fun checkParams(params: WXParams): Boolean {
        return !(params.appId.isEmpty() ||
                params.partnerId.isEmpty() ||
                params.prepayId.isEmpty() ||
                params.`package`.isEmpty() ||
                params.nonceStr.isEmpty() ||
                params.timestamp.isEmpty() ||
                params.sign.isEmpty()
                )
    }

    override fun release() {

    }
}
